package sample.Koans

import java.util.*

/**
 * Created by runjia on 17-6-1.
 */
fun <T> Collection<T>.partitionTo(first: MutableCollection<T>, second: MutableCollection<T>, predicate: (T) -> Boolean): Pair<Collection<T>, Collection<T>> {
    var list = partition(predicate)
    return Pair(list.component1().toCollection(first), list.component2().toCollection(second))
}

fun <T, P: MutableCollection<T>> Collection<T>.partitionTo2(first: P, second: P, predicate: (T) -> Boolean): Pair<P, P> {
    // Pair supports destruction
    var (f, s) = partition(predicate)
    return Pair(f.toCollection(first), s.toCollection(second))
}

fun partitionWordsAndLines() {
    val (words, lines) = listOf("a", "a b", "c", "d e").
            partitionTo(ArrayList<String>(), ArrayList()) { s -> !s.contains(" ") }
    println(words == listOf("a", "c"))
    println(lines == listOf("a b", "d e"))
}

fun partitionLettersAndOtherSymbols() {
    val (letters, other) = setOf('a', '%', 'r', '}').
            partitionTo(HashSet<Char>(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z' }
    println(letters == setOf('a', 'r'))
    println(other == setOf('%', '}'))
}

fun main(args: Array<String>) {
    partitionWordsAndLines()
    partitionLettersAndOtherSymbols()
}
